import os

from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers

from goods.models import SKUImage,SKU

from celery_tasks.static_html.tasks import get_detail_static


class SKUImageSerializer(serializers.ModelSerializer):
    class Meta:
        # 指定模型类
        model = SKUImage
        # 指定字段
        fields = ('id','sku','image')
    def create(self, validated_date):
        # 初始化生成连接对象
        client = Fdfs_client(os.path.join(settings.BASE_DIR,'utils/fasfdfs/client.conf'))
        # 获取图片数据
        image = validated_date['image']
        # 上传图片
        res = client.upload_by_buffer(image.read())
        # 判断图片是否上传成功
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        # 将图片在fasfDFS中连接地址保存在图片表
        image_path = res['Remote file_id']
        sku = validated_date['sku']
        img = SKUImage.objects.create(sku=sku,image=image_path)
        sku.default_image=image_path
        sku.save()
        # 详情静态化
        get_detail_static.delay(validated_date['sku'].id)
        return img
    def update(self, instance, validated_data):
        # 初始化生成连接对象
        client = Fdfs_client(os.path.join(settings.BASE_DIR, 'utils/fasfdfs/client.conf'))
        # 获取图片数据
        image = validated_data['image']
        # 上传图片
        res = client.upload_by_buffer(image.read())
        # 判断图片是否上传成功
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        # 将图片在fasfDFS中连接地址保存在图片表
        image_path = res['Remote file_id']

        instance.image = image_path
        instance.save()
        instance.sku.default_image = image_path
        instance.sku.save()
        return instance
class SKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields= ('id','name')


















